package com.example.hotelrear.controller;

import com.example.hotelrear.entity.Admin;
import com.example.hotelrear.entity.ResponseResult;
import com.example.hotelrear.service.AdminService;
import com.example.hotelrear.util.OssUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author FengXiao
 * @since 2023-08-28
 */
@RestController
@RequestMapping("/admin")
@CrossOrigin("*")
@Slf4j
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private OssUtil ossUtil;

    @PostMapping("/login")
    public ResponseResult login(@RequestParam("adminName") String adminName, @RequestParam("adminPassword") String adminPassword) {
        Admin admin = adminService.login(adminName, adminPassword);
        if (admin != null) {
            return ResponseResult.ok(admin);
        } else {
            return ResponseResult.fail();
        }
    }

    /**
     * 个人信息修改
     * @param admin
     * @return
     */
    @PostMapping("/update")
    public ResponseResult update(Admin admin,String url){
        adminService.updateAdmin(admin);
        if (admin!=null){
            return ResponseResult.ok(admin);
        }else {
            return ResponseResult.error("修改失败");
        }

    }
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public ResponseResult<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀  ****.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString()+ extension;

            String filePath = ossUtil.upload(file.getBytes(), objectName);
            System.out.println(filePath);
            return ResponseResult.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败",e);
        }
        return ResponseResult.error("文件上传失败");
    }

}
